package org.example;

import com.github.kwhat.jnativehook.GlobalScreen;
import com.github.kwhat.jnativehook.NativeHookException;
import com.github.kwhat.jnativehook.keyboard.NativeKeyEvent;
import com.github.kwhat.jnativehook.keyboard.NativeKeyListener;
import com.github.kwhat.jnativehook.mouse.NativeMouseEvent;
import com.github.kwhat.jnativehook.mouse.NativeMouseInputListener;
import java.awt.*;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;

/**
 * 对AHK2.0脚本的jdk1.8版
 * 此脚本需要建立Maven工程，pom文件需引入：
 * <dependencies>
 *         <dependency>
 *             <groupId>com.github.kwhat</groupId>
 *             <artifactId>jnativehook</artifactId>
 *             <version>2.2.2</version>
 *         </dependency>
 *     </dependencies>
 *
 *
 *  主要实现功能如下：
 *  1、手电筒自动爆闪： 当我按下 / 键时，进入一次持续20秒的监听。在监听中，如果检测到按下了鼠标左键，就立刻帮我按下]键。按下]键之后，监听立刻结束，结束监听方式有两个，一个是正常20秒结束，另一个是按下]键之后，监听立刻结束。
 *  2、右键自动屏息
 */
public class KeyboardListener implements NativeKeyListener, NativeMouseInputListener {
    private static final AtomicBoolean isListening = new AtomicBoolean(false);
    private static final AtomicReference<ScheduledExecutorService> timer = new AtomicReference<>();

    private static final ScheduledExecutorService rightClickScheduler = Executors.newScheduledThreadPool(1);
    private static final Robot robot;

    static {
        try {
            robot = new Robot();
        } catch (AWTException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        try {
            GlobalScreen.registerNativeHook();
        } catch (NativeHookException ex) {
            System.exit(1);
        }

        GlobalScreen.addNativeKeyListener(new KeyboardListener());
        GlobalScreen.addNativeMouseListener(new KeyboardListener());
    }

//    @Override
//    public void nativeKeyPressed(NativeKeyEvent e) {
//        // 当我按下 / 键时，进入一次持续20秒的监听
//        if (e.getKeyCode() == NativeKeyEvent.VC_SLASH) {
//            handleSlashPress();
//        }
//    }

    /**
     * 按下 鼠标上侧键 键时进入的监听器
     */
    private synchronized void handleSlashPress() {
        if (isListening.get()) {
            resetTimer();
        } else {
            startListener();
        }
    }

    /**
     * 鼠标左键触发爆闪
     * @param e
     */
    @Override
    public void nativeMousePressed(NativeMouseEvent e) {
        System.out.println(e.getButton());
        // BUTTON5是上侧键
        if (e.getButton() == NativeMouseEvent.BUTTON5){
            handleSlashPress();
        } else if (e.getButton() == NativeMouseEvent.BUTTON1 && isListening.get()) {
            // 处理左键，触发爆闪
            triggerCloseBracket();
            stopListener();
        } else if (e.getButton() == NativeMouseEvent.BUTTON2) {
            // 处理右键（自动屏息）
            scheduleBracketInput();
        }
    }

    /**
     * 按 ] 键，自动爆闪
     * .是开关手电的按钮。PC端必须开手电才能爆闪，这点和手机不同
     */
    private void triggerCloseBracket() {
        robot.keyPress('.');
        robot.keyRelease('.');
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {

        }
        robot.keyPress(']');
        robot.keyRelease(']');
    }
    /**
     * 按 [ 键，自动屏息
     */
    private void scheduleBracketInput() {
        rightClickScheduler.schedule(() -> {
            try {
                robot.keyPress('[');
                robot.keyRelease('[');
            } catch (Exception ex) {
                System.err.println("模拟按键失败: " + ex.getMessage());
            }
        }, 390, TimeUnit.MILLISECONDS);
    }
    private void startListener() {
        isListening.set(true);
        scheduleTimer();
    }

    private void resetTimer() {
        stopTimer();
        scheduleTimer();
    }

    private void scheduleTimer() {
        timer.set(Executors.newSingleThreadScheduledExecutor());
        timer.get().schedule(() -> {
            if (isListening.get()) {
                stopListener();
            }
        }, 20, TimeUnit.SECONDS);
    }

    private synchronized void stopListener() {
        isListening.set(false);
        stopTimer();
    }

    private void stopTimer() {
        if (timer.get() != null && !timer.get().isShutdown()) {
            timer.get().shutdownNow();
        }
    }

    // 需要实现的空方法
    @Override public void nativeKeyReleased(NativeKeyEvent e) {}
    @Override public void nativeKeyTyped(NativeKeyEvent e) {}
    @Override public void nativeMouseReleased(NativeMouseEvent e) {}
    @Override public void nativeMouseDragged(NativeMouseEvent e) {}
    @Override public void nativeMouseMoved(NativeMouseEvent e) {}
    @Override public void nativeMouseClicked(NativeMouseEvent e) {}
}